package com.dsit.hb950;

import android.util.Log;

import java.nio.ByteBuffer;

import protocol.CircularByteBuffer;

/**
 * Created by Administrator on 2016/12/2.
 */

public class CanbusDataFilter {
    final String TAG = "CanbusDataFilter";
    public interface CanbusDataFilterListener {
        void OnCanDataFrameReceive(ByteBuffer dataBuf);
    }

    CanbusDataFilterListener listener;
    CircularByteBuffer cbuf = new CircularByteBuffer(4*1024);

    int msgLen = 0;
    int headIndex = 0;
    byte[] frameBuf = null;

    public CanbusDataFilter() { }

    void d(String msg)
    {
        System.out.println("[CanDataFilter]:" + msg);
    }

    final int packesize = 39 * 4 + 4;// 39 *id + headsize
    public void onDataFiltering(byte[] data, int len)
    {
        d("--filtering ------- "+Utils.bytes2HexString(data,len));
        cbuf.WriteArray(data, len);
        while((headIndex = cbuf.IndexOf((byte)0x00,(byte)0x55,(byte)0xaa))!=-1){
            msgLen = packesize;
            d("in data len = "+len);
            d("head index = "+headIndex);
            d("CAN MsgLen = "+msgLen);
            // cbuf.info();
            if (cbuf.ReadableBytes() >= msgLen){
                byte[] outBuf = new byte[msgLen];
                cbuf.ReadArray(msgLen,outBuf);
                d("======output frame:::> "+Utils.bytes2HexString(outBuf,msgLen));
                if(listener!=null){
                   listener.OnCanDataFrameReceive(ByteBuffer.wrap(outBuf));
                }
            }else{
                break;
            }
        }
    }

    public void setLisenter(CanbusDataFilterListener lis){
        listener = lis;
    }

    public void reset()
    {
    }
}
